package com.qcxy.gzy.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qcxy.gyz.consts.CMDConts;
import com.qcxy.gzy.activity.base.BaseActivity;
import com.qcxy.gzy.bean.ComReceiveDataBean;
import com.qcxy.gzy.view.CircleChartView;
import com.qxcy.gzy.util.DataCovertUtil;
import com.qxcy.gzy.util.SPUtils;

public class LossFatActivity extends BaseActivity implements OnClickListener {

    private LinearLayout mNo1Layout;
    private LinearLayout mNo2Layout;
    private LinearLayout mNo3Layout;
    private LinearLayout mNo4Layout;
    private LinearLayout mNo5Layout;

    protected TextView finish;
    /**
     * 组数
     */
    private int mRealGroups = 1;

    private TextView mTimeTv;

    private boolean firstTime = true;
    private boolean isCountDown = true;
    /**
     * 实际重量
     */
    private int mWeight;
    /**
     * 计算器
     */
    private Calendar mCalendar = Calendar.getInstance();

    private TextView showTargetNumber;
    private TextView mCalorieTv;
    private TextView mShowWeight;
    private TextView mShowRealGroups;

    private CircleChartView mDialChartView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loss_fat);

        findViewById(R.id.iv_back).setOnClickListener(this);

        showTargetNumber = (TextView) findViewById(R.id.report_number);
        mShowRealGroups = (TextView) findViewById(R.id.report_number1);
        mTimeTv = (TextView) findViewById(R.id.report_number2);
        mCalorieTv = (TextView) findViewById(R.id.report_number3);
        mShowWeight = (TextView) findViewById(R.id.report_number4);

        findViewById(R.id.zl_zj).setOnClickListener(this);
        findViewById(R.id.zl_js).setOnClickListener(this);

        mNo1Layout = (LinearLayout) findViewById(R.id.ll_no1);
        mNo2Layout = (LinearLayout) findViewById(R.id.ll_no2);
        mNo3Layout = (LinearLayout) findViewById(R.id.ll_no3);
        mNo4Layout = (LinearLayout) findViewById(R.id.ll_no4);
        mNo5Layout = (LinearLayout) findViewById(R.id.ll_no5);

        mDialChartView = (CircleChartView) findViewById(R.id.myview_circle_chart);

        finish = (TextView) findViewById(R.id.finish);

        MAX_STRENGTH = Integer.parseInt(SPUtils.getValueFromSharedFile(LossFatActivity.this, "MAX_STRENGTH", "0"));
        MAX_DISTANCE = Integer.parseInt(SPUtils.getValueFromSharedFile(LossFatActivity.this, "MAX_DISTANCE", "0"));
        if (MAX_STRENGTH == 0 || MAX_DISTANCE == 0) {
            Toast.makeText(this, "您没有进行力量和距离检测", Toast.LENGTH_LONG).show();
            MAX_STRENGTH = 20;
            MAX_DISTANCE = 3500;
        }
        mWeight = (int) (MAX_STRENGTH * 0.5);

        mShowWeight.setText(mWeight + "");
        setTextSelectionBg(R.id.ll_no1);
        mShowRealGroups.setText(mRealGroups + "");
        mDialChartView.setPercent(0, MAX_DISTANCE * 100 / 3500);

        // 新建发送任务
        mSendThread = new SendThread(getForceCMD(mWeight), false);
        mSendThread.start();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.iv_back:
                SPUtils.setValueSharedFile(LossFatActivity.this, "MAX_STRENGTH", "0");
                SPUtils.setValueSharedFile(LossFatActivity.this, "MAX_DISTANCE", "0");
                cancelTimer();
                LossFatActivity.this.finish();
                break;

            case R.id.zl_zj:
                if (mWeight < 100) {
                    mWeight++;
                    mShowWeight.setText(mWeight + "");
                } else {
                    Toast.makeText(LossFatActivity.this, R.string.max_weight,
                            Toast.LENGTH_SHORT).show();
                }
                // 定时开始
                if (weightTime != null) {
                    weightTime.cancel();
                    weightTime.purge();
                    weightTime = null;
                }
                weightTime = new Timer();
                weightTime.schedule(new weightChangeTask(), 2000);
                break;


            case R.id.zl_js:
                if (mWeight > 10) {
                    mWeight--;
                    mShowWeight.setText(mWeight + "");
                } else {
                    Toast.makeText(LossFatActivity.this, R.string.min_weight,
                            Toast.LENGTH_SHORT).show();
                }
                // 定时开始
                if (weightTime != null) {
                    weightTime.cancel();
                    weightTime.purge();
                    weightTime = null;
                }
                weightTime = new Timer();
                weightTime.schedule(new weightChangeTask(), 2000);
                break;
        }
    }

    /**
     * 根据命令设置背景颜色
     *
     * @param resId
     */
    public void setTextSelectionBg(int resId) {
        switch (resId) {
            case R.id.ll_no1: {
                mNo1Layout.setBackgroundResource(R.drawable.ic_textview_bg);
                mNo2Layout.setBackground(null);
                mNo3Layout.setBackground(null);
                mNo4Layout.setBackground(null);
                mNo5Layout.setBackground(null);
                break;
            }
            case R.id.ll_no2: {
                mNo2Layout.setBackgroundResource(R.drawable.ic_textview_bg);
                mNo1Layout.setBackground(null);
                mNo3Layout.setBackground(null);
                mNo4Layout.setBackground(null);
                mNo5Layout.setBackground(null);
                break;
            }
            case R.id.ll_no3: {
                mNo3Layout.setBackgroundResource(R.drawable.ic_textview_bg);
                mNo2Layout.setBackground(null);
                mNo1Layout.setBackground(null);
                mNo4Layout.setBackground(null);
                mNo5Layout.setBackground(null);
                break;
            }
            case R.id.ll_no4: {
                mNo4Layout.setBackgroundResource(R.drawable.ic_textview_bg);
                mNo2Layout.setBackground(null);
                mNo3Layout.setBackground(null);
                mNo1Layout.setBackground(null);
                mNo5Layout.setBackground(null);
                break;
            }
            case R.id.ll_no5: {
                mNo5Layout.setBackgroundResource(R.drawable.ic_textview_bg);
                mNo2Layout.setBackground(null);
                mNo3Layout.setBackground(null);
                mNo4Layout.setBackground(null);
                mNo1Layout.setBackground(null);
                break;
            }

            default:
                break;
        }
    }

    /**
     * 获得力量数据
     *
     * @param maxStrength 用户测定最大力量，单位牛顿
     * @return
     */
    protected List<byte[]> getForceCMD(int maxStrength) {
        List<String> forceList = null;
        StringBuilder sDistance_D2 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D3 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D4 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D5 = new StringBuilder(); // 存放写入力量寄存器2命令
        int distance_3 = 0; // 存放距离寄存器3的值
        List<byte[]> cmdList = new ArrayList<byte[]>(); // 命令列表
        List<String> forceHeadList = new ArrayList<String>(); // 写入力量命令列表
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F1); // 添加命令头部
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F2);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F3);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F4);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F5);
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_F0);

        forceList = getConstantForce(maxStrength);

        if (forceList != null) {
            for (int i = 0; i < forceHeadList.size(); i++) {
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.append(forceHeadList.get(i)); // 添加头部
                sBuilder.append(forceList.get(i)); // 添加力量值
                // 获得并添加CRC校验码
                cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sBuilder.toString())));
            }
        }
        distance_3 = (80 + MAX_DISTANCE) / 2; // 计算距离寄存器D3的值
        sDistance_D2.append(CMDConts.CMD_WRITE_REIGSTER_D2); // 添加头部
        sDistance_D2.append(DataCovertUtil.get4LenString(Integer.toHexString((80 + distance_3) / 2))); // 计算并添加距离值
        sDistance_D3.append(CMDConts.CMD_WRITE_REIGSTER_D3); // 添加头部
        sDistance_D3.append(DataCovertUtil.get4LenString(Integer.toHexString(distance_3))); // 添加距离值
        sDistance_D4.append(CMDConts.CMD_WRITE_REIGSTER_D4); // 添加头部
        sDistance_D4.append(DataCovertUtil.get4LenString(Integer.toHexString((distance_3 + MAX_DISTANCE) / 2)));// 添加距离值
        sDistance_D5.append(CMDConts.CMD_WRITE_REIGSTER_D5); // 添加头部
        sDistance_D5.append(DataCovertUtil.get4LenString(Integer.toHexString(MAX_DISTANCE))); // 添加距离值
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D0); // 添加距离寄存器D0的命令
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D1); // 添加距离寄存器D1的命令
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D2.toString()))); // 计算并添加距离寄存器D2命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D3.toString()))); // 计算并添加距离寄存器D3命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D4.toString()))); // 计算并添加距离寄存器D4命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D5.toString()))); // 计算并添加距离寄存器D5命令的CRC校验码
        cmdList.add(CMDConts.CMD_READ_REGISTER_3_4); // 添加读取寄存器3、4命令
        return cmdList;
    }

    /**
     * 获得恒力力量
     *
     * @param maxStrength
     * @return
     */
    private List<String> getConstantForce(int maxStrength) {
        List<String> list = new ArrayList<String>();
        String force = DataCovertUtil.get4LenString(Integer.toHexString((int) (33.33 * maxStrength))); // 获得四位字符串型力量的值
        list.add(force);
        list.add(force);
        list.add(force);
        list.add(force);
        list.add(force);
        return list;
    }

    private void resetCalendar() {
        mCalendar.set(Calendar.HOUR_OF_DAY, 0);
        mCalendar.set(Calendar.MINUTE, 0);
        mCalendar.set(Calendar.SECOND, 0);
    }

    private Timer mTimer4LogOut = null;

    private void resetTimer4LogOut() {
        if (mTimer4LogOut != null) {
            mTimer4LogOut.cancel();
            mTimer4LogOut.purge();
            mTimer4LogOut = null;
        }
        mTimer4LogOut = new Timer();
        // 1分钟不操作自动上传数据
        mTimer4LogOut.schedule(new Task4Logout(), 1 * 60 * 1000);
    }

    private class Task4Logout extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    // uploadTrainningData();
                    LossFatActivity.this.finish();
                }
            });
        }
    }

    private Timer timer;

    private void showClock(TextView tv) {
        timer = new Timer();
        timer.schedule(new TrainTask(tv), 1000, 1000);
    }

    private class TrainTask extends TimerTask {
        public TrainTask(TextView tv) {
            mTimeTv = tv;
        }

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    // 每次秒数+1
                    mCalendar.add(Calendar.SECOND, 1);
                    mTimeTv.setText(DataCovertUtil.get2LenString(mCalendar.get(Calendar.MINUTE)) + ":" + DataCovertUtil.get2LenString(mCalendar.get(Calendar.SECOND)));
                }
            });
        }
    }

    private Timer mChronometer;

    private class CountDown extends TimerTask {

        public CountDown(TextView tv) {
            mCalendar.set(Calendar.SECOND, 30);
            mCalendar.set(Calendar.MINUTE, 0);
            mCalendar.set(Calendar.HOUR_OF_DAY, 0);
            mTimeTv = tv;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            runOnUiThread(new Runnable() {
                public void run() {
                    // 每次秒数-1
                    mCalendar.add(Calendar.SECOND, -1);
                    mTimeTv.setText(DataCovertUtil.get2LenString(mCalendar.get(Calendar.MINUTE)) + ":" + DataCovertUtil.get2LenString(mCalendar.get(Calendar.SECOND)));
                    if (mCalendar.get(Calendar.SECOND) == 0) {
                        mChronometer.cancel();
                        isCountDown = true;
                        showClock(mTimeTv);
                        mRealGroups++;
                        mShowRealGroups.setText(mRealGroups + "");
                        mRealCounts = 0;
                        if (mRealGroups == 2) {
                            mWeight = (int) (MAX_STRENGTH * 0.45);
                            setTextSelectionBg(R.id.ll_no2);
                            closeSendThread();
                            // 新建发送任务
                            mSendThread = new SendThread(getForceCMD(mWeight), false);
                            mSendThread.start();
                        } else if (mRealGroups == 3) {
                            mWeight = (int) (MAX_STRENGTH * 0.40);
                            setTextSelectionBg(R.id.ll_no3);
                            closeSendThread();
                            // 新建发送任务
                            mSendThread = new SendThread(getForceCMD(mWeight), false);
                            mSendThread.start();
                        } else if (mRealGroups == 4) {
                            mWeight = (int) (MAX_STRENGTH * 0.35);
                            setTextSelectionBg(R.id.ll_no4);
                            closeSendThread();
                            // 新建发送任务
                            mSendThread = new SendThread(getForceCMD(mWeight), false);
                            mSendThread.start();
                        } else {
                            setTextSelectionBg(R.id.ll_no5);
                        }
                        mShowWeight.setText(mWeight + "");
                    }
                }
            });
        }
    }

    private Timer weightTime;

    private class weightChangeTask extends TimerTask {
        @Override
        public void run() {
            closeSendThread();
            mSendThread = new SendThread(getForceCMD(mWeight), false);
            mSendThread.start();
        }
    }

    private void cancelTimer() {
        if (timer != null) {
            timer.cancel();
        }
        if (mChronometer != null) {
            mChronometer.cancel();
        }
        if (mTimer4LogOut != null) {
            mTimer4LogOut.cancel();
        }
        if (weightTime != null) {
            weightTime.cancel();
        }
    }

    private int distance = 0;

    @Override
    protected void onDataReceived(ComReceiveDataBean ComRecData) {

        if (ComRecData.getCRC(ComRecData.bRec).equals("0")) {
            String res = DataCovertUtil.ByteArrToHex(ComRecData.bRec);
            final int control = DataCovertUtil.HexToInt(DataCovertUtil
                    .ByteArrToHex(ComRecData.bRec).substring(2, 4));
            if (control == 3) { // control指的返回的命令区分码
                // 实时值
                // final int weight = DataCovertUtil
                // .HexToInt(res.substring(6, 10));
                distance = DataCovertUtil.HexToInt(res.substring(10,
                        14));
                if (distance > 150) {
                    if (firstTime) {
                        resetCalendar();
                        showClock(mTimeTv);
                        firstTime = false;
                    }
                    resetTimer4LogOut();
                }

                if (distance >= MAX_DISTANCE * 0.8) { // 检测到距离大于60%最大距离时
                    mStatus = 1; // 拉伸状态变为1
                    if (distance4Calorie < distance) {
                        distance4Calorie = distance;
                    }
                }

                // 拉伸状为1并且 检测到距离小于30%最大距离时拉伸状态变为
                if (mStatus == 1 && distance < MAX_DISTANCE * 0.2) {
                    mRealCounts++; // 次数 + 1
                    mStatus = 0; // 拉伸状态清除

                    if (distance4Calorie >= 1500 && distance4Calorie < 2000) {
                        calorie = calorie + (mWeight / (180 + (Math.random() * 40)));
                    } else if (distance4Calorie >= 2000 && distance4Calorie < 3000) {
                        calorie = calorie + (mWeight / (130 + (Math.random() * 40)));
                    } else {
                        calorie = calorie + (mWeight / (80 + (Math.random() * 40)));
                    }
                }
            }

            if (mRealGroups == 1) {
                if (mRealCounts == 20) {
                    if (isCountDown) {
                        timer.cancel();
                        // 开启倒计时模式的计时器
                        mChronometer = new Timer();
                        mChronometer.schedule(new CountDown(mTimeTv), 1000, 1000);
                        isCountDown = false;
                    }
                }
            } else if (mRealGroups == 2) {
                if (mRealCounts == 25) {
                    if (isCountDown) {
                        timer.cancel();
                        // 开启倒计时模式的计时器
                        mChronometer = new Timer();
                        mChronometer.schedule(new CountDown(mTimeTv), 1000, 1000);
                        isCountDown = false;
                    }
                }
            } else if (mRealGroups == 3) {
                if (mRealCounts == 25) {
                    if (isCountDown) {
                        timer.cancel();
                        // 开启倒计时模式的计时器
                        mChronometer = new Timer();
                        mChronometer.schedule(new CountDown(mTimeTv), 1000, 1000);
                        isCountDown = false;
                    }
                }
            } else if (mRealGroups == 4) {
                if (mRealCounts == 30) {
                    if (isCountDown) {
                        timer.cancel();
                        // 开启倒计时模式的计时器
                        mChronometer = new Timer();
                        mChronometer.schedule(new CountDown(mTimeTv), 1000, 1000);
                        isCountDown = false;
                    }
                }
            } else {
                if (mRealCounts == 30) {
                    if (isCountDown) {
                        timer.cancel();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mNo2Layout.setVisibility(View.GONE);
                                mNo3Layout.setVisibility(View.GONE);
                                mNo4Layout.setVisibility(View.GONE);
                                mNo5Layout.setVisibility(View.GONE);
                                mNo1Layout.setVisibility(View.GONE);
                                finish.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showTargetNumber.setText(mRealCounts + "");
                    mCalorieTv.setText(String.format("%.1f", calorie));
                    mDialChartView.setPercent(distance * 100 / 3500, MAX_DISTANCE * 100 / 3500);
                }
            });
        }
    }
}
